import { Provide, Inject } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository, In } from 'typeorm';
import { ApplyFriendDTO } from '../dto/friend';
import { FriendApplyEntity } from '../entity/friendApply';
import { FriendEntity } from '../entity/friend';
import { UserEntity } from '../entity/user';

import { message, TokenUtil } from '@/util/index';

@Provide()
export class FriendService {
  @InjectEntityModel(FriendApplyEntity)
  friendApplyEntity: Repository<FriendApplyEntity>;

  @InjectEntityModel(FriendEntity)
  friendEntity: Repository<FriendEntity>;

  @InjectEntityModel(UserEntity)
  userEntity: Repository<UserEntity>;

  @Inject()
  tokenUtil: TokenUtil;

  /**
   * 申请添加好友
   */
  async applyFriend(applyFriend: ApplyFriendDTO) {
    const userToken: any = await this.tokenUtil.verifyToken();

    const params = {
      originId: Number(applyFriend.friendId),
      userId: Number(applyFriend.friendId),
      friendId: userToken.payload.userId,
      userName: applyFriend.friendName,
      friendName: applyFriend.userName,
      userImage: applyFriend.friendImage,
      friendImage: applyFriend.userImage,
      msg: applyFriend.msg,
      status: 2, // 1: 已经是好友；2: 申请添加好友；3: 拒绝添加好友
    };
    await this.friendApplyEntity.save(params);
    return message.success(200, '申请成功');
  }

  /**
   * 获取好友申请列表
   */
  async getFriendApplyList() {
    const userToken: any = await this.tokenUtil.verifyToken();

    const result = await this.friendApplyEntity.find({
      where: [
        { userId: userToken.payload.userId },
        { friendId: userToken.payload.userId },
      ],
      order: {
        id: 'DESC',
      },
    });
    const formatData: any = [];
    result.forEach((item: any) => {
      if (Number(userToken.payload.userId) === item.userId) {
        // console.log('2 接受方', item);
        formatData.push({
          // userId: item.friendId,
          id: item.id,
          friendId: item.friendId,
          name: item.friendName,
          msg: item.msg,
          imgUrl: item.friendImage,
          status: item.status,
          createTime: item.createTime,
          updateTime: item.updateTime,
          userType: 2, // 1 申请方 2 接受方
        });
      } else {
        // console.log('1 申请方', item);
        formatData.push({
          // userId: item.userId,
          id: item.id,
          originId: item.originId,
          friendId: item.friendId,
          name: item.userName,
          msg: item.msg,
          imgUrl: item.userImage,
          status: item.status,
          createTime: item.createTime,
          updateTime: item.updateTime,
          userType: 1, // 1 申请方 2 接受方
        });
      }
    });
    return message.success(200, '获取成功', formatData);
  }

  /**
   * 更新好友状态
   */
  async updateFriendStatus(options: ApplyFriendDTO) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = Number(userToken.payload.userId);
    const result = await this.friendApplyEntity.findOne({
      where: { userId: userToken.payload.userId, status: 2 },
    });
    result.status = options.status;
    const params = {
      userId,
      friendId: options.friendId,
    };

    if (options.status === 1) {
      await this.friendEntity.save(params);
    }
    await this.friendApplyEntity.save(result);

    return message.success(200, '更新成功');
  }

  /**
   * 获取好友列表
   */
  async getFriendList() {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    const arrData: any = [userId];

    const data = await this.friendEntity.find({
      where: [{ userId }, { friendId: userId }],
    });
    // const result = await this.friendEntity.find({
    //   where: [{ userId }, { friendId: userId }],
    //   relations: ['users'],
    //   select: ['users'],
    // });
    data.forEach(item => {
      console.log('item', item);
      arrData.push(item.userId);
      arrData.push(item.friendId);
    });
    console.log('formatData', arrData);
    const formatData = [];
    const result = await this.userEntity.find({
      where: {
        id: In(arrData),
      },
      select: ['id', 'username', 'imgUrl', 'desc'],
    });
    result.forEach(item => {
      if (item.id === userId) {
        formatData.push({
          type: 1,
          id: item.id,
          username: item.username,
          imgUrl: item.imgUrl,
          desc: item.desc,
        });
      } else {
        formatData.push({
          type: 2,
          id: item.id,
          username: item.username,
          imgUrl: item.imgUrl,
          desc: item.desc,
        });
      }
    });
    console.log('result', result);
    return message.success(200, '获取好友列表', formatData);
    // return message.success(200, '获取好友列表', []);
  }

  /**
   * 获取好友详情
   */
  async login(id: number) {
    const result = await this.userEntity
      .createQueryBuilder('user')
      .select([
        'user.id',
        'user.username',
        'user.account',
        'user.email',
        'user.sex',
        'user.birth',
        'user.phone',
        'user.desc',
        'user.imgUrl',
        'user.createTime',
        'user.updateTime',
      ])
      .where({
        id: id,
      })
      .getMany();
    return message.success(200, '获取好友详情', result);
  }

  /**
   * 删除好友
   */
  async deleteFriend(id: number) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = Number(userToken.payload.userId);
    console.log('id: ', id);
    console.log('userId: ', userId);
    const result = await this.friendEntity
      .createQueryBuilder()
      .delete()
      .where([
        {
          friendId: userId,
          userId: id,
        },
        {
          friendId: id,
          userId: userId,
        },
      ])
      .execute();
    console.log('result: ', result);
    return message.success(200, '删除成功', result);
  }
}
